package com.guoqi.oabridge


import android.os.Handler
import android.os.Looper
import com.alibaba.fastjson.JSONException
import com.alibaba.fastjson.JSONObject
import com.tencent.smtt.sdk.WebView
import java.lang.ref.WeakReference

class Callback(view: WebView, private val mPort: String) {
    private val mWebViewRef: WeakReference<WebView>?

    init {
        mWebViewRef = WeakReference(view)
    }


    fun apply(jsonObject: JSONObject) {
        val execJs = String.format(CALLBACK_JS_FORMAT, mPort, jsonObject.toString())
        if (mWebViewRef?.get() != null) {
            mHandler.post { mWebViewRef.get()!!.loadUrl(execJs) }
        }
    }

    companion object {
        val mHandler = Handler(Looper.getMainLooper())
        const val CALLBACK_JS_FORMAT = "javascript:JSBridge.onFinish('%s', %s);"

        fun setSuccess(result: JSONObject): JSONObject {
            return getJSONObject(0, "ok", result)!!
        }

        fun setSuccess(): JSONObject {
            return getJSONObject(0, "ok", JSONObject())!!
        }

        fun setFailed(err: String): JSONObject {
            return getJSONObject(1, "err", JSONObject())!!
        }


        private fun getJSONObject(code: Int, msg: String, result: JSONObject): JSONObject? {
            val obj = JSONObject()
            try {
                obj["code"] = code
                obj["msg"] = msg
                obj["sendData"] = result
                return obj
            } catch (e: JSONException) {
                e.printStackTrace()
            }
            return null
        }
    }
}